<template>
  <div id="LabTMLBDict">
    <Breadcrumb content="视图列表" />
    <div class="bodyContent">
      <!-- vxe-toolbar -->
      <Splitpanes class="area">
        <Pane size="10">
          <div class="tableBox">
            <vxe-table ref="tableRef" border="inner" align="left" class="mytable-scrollbar" :loading="loading" height="auto" :data="viewsTypeList" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }" @current-change="tableCellClick">
              <vxe-column field="code" title="编码"> </vxe-column>
              <vxe-column field="name" title="名称"> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input type="search" v-model="form.keyvalue" clearable class="vxeInputSearch" @search-click="findList" @clear="findList" @keyup.enter="findList" placeholder="关键字查询"></vxe-input>
              <vxe-button type="text" class="button-blue" @click="findList" icon="vxe-icon-refresh" :loading="loading">刷新</vxe-button>
              <vxe-button type="text" class="button-red" @click="deleteSampleType" icon="vxe-icon-delete">删除</vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="tableRef111" border="inner" align="left" class="mytable-scrollbar" :cell-style="calcCellBgColor" :loading="loading" height="auto" :data="tableData" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }" @current-change="midTableCellClick">
              <vxe-column type="checkbox" width="26"></vxe-column>
              <vxe-column type="seq" title="#" width="30"></vxe-column>
              <vxe-column field="name" title="名称" width="120"> </vxe-column>
              <vxe-column field="title" title="标题" width="120"> </vxe-column>
              <vxe-column field="viewType" title="类型" width="60">
                <template #default="{ row }">
                  {{ getmessTypeName(row) }}
                </template> </vxe-column>
              <vxe-column field="costTime" title="耗时" width="60"> </vxe-column>
              <vxe-column field="applyName" title="申请人" width="100"> </vxe-column>
              <vxe-column field="applyTime" title="申请时间" width="120"> </vxe-column>
              <vxe-column field="auditName" title="审核人" width="100"> </vxe-column>
              <vxe-column field="auditTime" title="审核时间" width="120"> </vxe-column>
              <vxe-column field="content" title="内容"> </vxe-column>
              <vxe-column field="remark" title="功能描述" min-width="150"> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="40">
          <el-tabs type="border-card">
            <el-tab-pane label="基本信息">
              <el-scrollbar style="height: 100%">
                <el-divider content-position="left">视图基本信息
                </el-divider>
                <el-form ref="viewFormRef" :model="viewForm" label-width="100px" class="form-input-m" inline-message disabled>
                  <el-form-item prop="title" label="标题">
                    <el-input type="text" v-model="viewForm.title" placeholder="请输入标题" clearable></el-input>
                  </el-form-item>
                  <el-form-item prop="name" label="名称（SQL）">
                    <el-input type="text" v-model="viewForm.name" placeholder="请输入名称" clearable></el-input>
                  </el-form-item>
                  <el-form-item prop="viewType" label="类型">
                    <el-select v-model="viewForm.viewType" filterable placeholder="请选择工作组" style="width: 200px">
                      <el-option v-for="messType in viewsTypeList" :key="messType.code" :label="messType.name" :value="messType.code"></el-option>
                    </el-select>
                  </el-form-item>
                  <!-- <el-form-item prop="viewSource" label="来源">
                  <el-input type="text" v-model="viewForm.viewSource" placeholder="请输入来源" clearable></el-input>
                </el-form-item> -->
                  <el-form-item label="功能说明" prop="remark">
                    <el-input v-model="viewForm.remark" placeholder="请输入说明" clearable type="textarea" :autosize="{ minRows: 5, maxRows: 5 }" style="width: 560px"></el-input>
                  </el-form-item>
                  <el-form-item label="视图内容" prop="content">
                    <el-input v-model="viewForm.content" placeholder="请输入视图内容" clearable type="textarea" :autosize="{ minRows: 5, maxRows: 10 }" style="width: 560px"></el-input>
                  </el-form-item>
                </el-form>
                <el-tabs type="border-card" @tab-click="tabHandleClick">
                  <el-tab-pane label="预览数据">
                    <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="预览" @click="testSqlView"></vxe-button>
                    <div class="tableBody">
                      <vxe-table ref="viewTableRef" class="mytable-scrollbar" border height="300px;" align="left" :data="viewList" :loading="showLoading" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }" resizable show-overflow>
                        <vxe-column v-for="item in coloumList" :key="item" :field="item" :title="item" width="120"> </vxe-column>
                      </vxe-table>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="调用日志">
                    <div class="tableBody">
                      <vxe-table ref="tableRef222" border="inner" align="left" class="mytable-scrollbar" :loading="loading" height="300px" :data="tableLogData" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }">
                        <vxe-column type="seq" title="#" width="30"></vxe-column>
                        <vxe-column field="name" title="名称"> </vxe-column>
                        <vxe-column field="costTime" title="耗时"> </vxe-column>
                        <vxe-column field="executor" title="调用人"> </vxe-column>
                        <vxe-column field="executName" title="调用人姓名"> </vxe-column>
                        <vxe-column field="executTime" title="调用时间"> </vxe-column>
                      </vxe-table>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </el-scrollbar>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import { AppStore } from '@/stores/store';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();

// 左侧表格:
const loading = ref(false); //刷新+表格加载
const form = reactive({
  keyvalue: '',
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName,
  code: ''
}); //根据关键字查询
const tableRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记
const tableRef111 = ref<VxeTableInstance<RowVO>>(); //表格ref标记
const tableData = reactive([]); //表格数据
const viewsTypeList = reactive([]);
const viewForm = reactive({ id: '', title: '', name: '', content: '', remark: '', status: '', viewType: '' });
let viewList: any = reactive([]);
let tableLogData = reactive([]); //表格数据
let coloumList: any = reactive([]);
let showLoading = ref(false); //刷新加载状态

// 方法定义区 =============
onMounted(() => {
  getDictDetailList();
});

function getDictDetailList() {
  viewsTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'viewTypes' } })
    .then(async (res: any) => {
      viewsTypeList.push(...res.data);
      tableCellClick({ row: res.data[0] });
      const $table = tableRef.value;
      if ($table) {
        await $table.setCurrentRow(res.data[0]);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 表格选中当前行
function tableCellClick({ row }: any) {
  Object.assign(form, row);
  findList();
}

function getmessTypeName(row) {
  // proxy.$nextTick(() => {
  if (viewsTypeList.length > 0) {
    const group = viewsTypeList.find((item) => item.code == row.viewType);
    return group ? group.name : '';
  }
}

function testSqlView() {
  showLoading.value = true;
  const url = '/view/apply/getViewApplyTestResultList';
  viewList.length = 0; //放入数据前清空数据
  coloumList.length = 0;
  proxy.$http
    //注意此处的数据条数
    .post(url, { sql: viewForm.content, id: viewForm.id, name: viewForm.name })
    .then((res: any) => {
      showLoading.value = false;
      coloumList.push(...res.data.coloums);
      viewList.push(...res.data.data);
    })
    .catch((err: any) => {
      showLoading.value = false;
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}

// 获取 样本类型表格数据
const findList = () => {
  loading.value = true;
  tableData.length = 0; //放入数据前清空数据
  clearViewForm();
  const url = '/view/apply/getViewApplyList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { keyWords: form.keyvalue, orgId: form.orgId, viewSource: 2, viewType: form.code } })
    .then(async (res: any) => {
      if (res && res.data && res.data.length > 0) {
        tableData.push(...res.data);
        midTableCellClick({ row: res.data[0] });
        const $table = tableRef111.value;
        if ($table) {
          await $table.setCurrentRow(res.data[0]);
        }
      }
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取视图列表数据异常', VxeNotifyType.error);
    });
};

function midTableCellClick({ row }: any) {
  clearViewForm();
  Object.assign(viewForm, row);
  //查询日志信息
  findLogList(viewForm);
}

function calcCellBgColor({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  if (row.costTime.replace('ms', '') > 3000) {
    return { background: '#FF9900', color: '#fff' };
  }
}
function findLogList(viewForm) {
  tableLogData.length = 0;
  const url = '/view/apply/getViewLogsByName';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { name: viewForm.name } })
    .then(async (res: any) => {
      if (res && res.data && res.data.length > 0) {
        tableLogData.push(...res.data);
      }
    })
    .catch((err: any) => {
      VxeMessage('获取视图日志数据异常', VxeNotifyType.error);
    });
}

function tabHandleClick(tab) {
  console.log(tab);
  if (tab.index == 1) {
    findLogList(viewForm);
  }
}

function clearViewForm() {
  //pnameShow.value = false;
  viewForm.id = '';
  viewForm.title = '';
  viewForm.name = '';
  viewForm.content = '';
  viewForm.remark = '';
  viewForm.status = '';
  viewForm.viewType = '';
  viewList.length = 0;
  coloumList.length = 0;
}
</script>
<style lang="scss" scoped>
#LabTMLBDict {
  width: 100%;
  height: 100%;
  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBox {
        height: calc(100% - 40px);
      }
    }
  }
}
</style>
